import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actions from '../actions/index';
import { Loading, Balloon } from '@teamix/ui';
import { Section, ButtonIcon } from '@alife/devops-ui';
import { enterPage, Perf } from 'utils/track';
import docs from 'utils/docs';
import { getFeature } from 'utils/features';
import BaseForm from './baseForm';
import CryptoForm from './cryptoForm';
import DagenrousForm from './dagenrousForm';
import StorageForm from './storageForm';
import intl from '../../../../../../../../../locale';

const { pathResource } = window.FORCE;

class Root extends Component {
  static propTypes = {
    saveGeneral: PropTypes.func,
    searchBranches: PropTypes.func,
    searchNamespaces: PropTypes.func,
    archiveOrUnarchive: PropTypes.func,
    transfer: PropTypes.func,
    rename: PropTypes.func,
    projectInfo: PropTypes.object,
    remove: PropTypes.func,
    isForked: PropTypes.bool,
    sourceProjectVisibilityLevel: PropTypes.number,
    isRemoving: PropTypes.bool,
  };

  static defaultProps = {
    saveGeneral: () => {},
    searchBranches: () => {},
    searchNamespaces: () => {},
    archiveOrUnarchive: () => {},
    remove: () => {},
    transfer: () => {},
    rename: () => {},
    projectInfo: null,
    isForked: null,
    sourceProjectVisibilityLevel: null,
    isRemoving: false,
  };

  state = {
    is_crypto_enabled: false,
  };

  componentDidMount() {
    const fullName = pathResource.fullName.split('/')[1]
      ? pathResource.fullName.split('/')[1].trim()
      : '';
    document.title = intl.get(
      {
        id: 'code-assets.settings.containers.root.BasicSettingsFullnameCloudEffect',
        defaultMessage: '基本设置 · {fullName} · 云效 Codeup',
      },
      { fullName },
    );
    this.props.getProject();
    this.props.checkIsForked();
    enterPage('Repo-Settings', {
      sendPerf: false,
    });
  }

  setDeleteBtnDisableByCrypto = (is_crypto_enabled) => {
    this.setState({
      is_crypto_enabled,
    });
  };

  componentWillUnmount() {
    this.props.clearTimer();

    // 清空数据
    this.props.resetData();
  }
  // 是否展示存储空间表单项
  notShowStorageForm = () => {
    if (!getFeature('project.setting.basic_setting.storage')) {
      return true;
    }
    if (window.FORCE.pathResource.isEmpty === 'true') {
      return true;
    }
    return false;
  };

  render() {
    const {
      projectInfo,
      saveGeneral,
      searchBranches,
      searchNamespaces,
      archiveOrUnarchive,
      transfer,
      rename,
      remove,
      isTransferring,
      isForked,
      sourceProjectVisibilityLevel,
      isRemoving,
    } = this.props;

    const { is_crypto_enabled } = this.state;

    const isLoading =
      projectInfo === null ||
      isForked === null ||
      (isForked && sourceProjectVisibilityLevel === null);
    return (
      <div className="base-setting-main">
        {isLoading ? (
          <div className="setting-loading">
            <Loading />
          </div>
        ) : (
          <>
            {!!projectInfo && (
              <>
                <Section
                  title={intl.get({
                    id: 'code-assets.containers.baseForm.BasicInformation',
                    defaultMessage: '基本信息',
                  })}
                >
                  <BaseForm
                    id={projectInfo.id}
                    visibilityLevel={projectInfo.visibility_level}
                    description={projectInfo.description}
                    defaultBranch={projectInfo.default_branch}
                    name={projectInfo.name}
                    path={projectInfo.path}
                    tagList={projectInfo.tag_list}
                    saveGeneral={saveGeneral}
                    searchBranches={searchBranches}
                    namespaceVisibilityLevel={projectInfo.namespace.visibility_level}
                    avatarUrl={projectInfo.avatar_url}
                    isReview={projectInfo.is_review}
                    exceptBranch={projectInfo.except_branch}
                    checkemail={projectInfo.checkemail}
                    isForked={isForked}
                    sourceProjectVisibilityLevel={sourceProjectVisibilityLevel}
                    admin_setting_language={projectInfo.admin_setting_language}
                    clone_download_info={{
                      project_clone_download_role_list:
                        projectInfo.project_clone_download_role_list,
                      project_clone_download_method_list:
                        projectInfo.project_clone_download_method_list,
                      enable_clone_download_control: projectInfo.enable_clone_download_control,
                      open_clone_download_control: projectInfo.open_clone_download_control,
                      clone_download_control_gray: projectInfo.clone_download_control_gray,
                    }}
                  />
                </Section>
                <Perf page="Repo-Settings" />
                {
                  getFeature('project.setting.project_encrypt') ?
                    <Section
                      title={
                        <>
                          {intl.get({
                            id: 'code-assets.containers.cryptoForm.RepositoryEncryption',
                            defaultMessage: '仓库加密',
                          })}
                          <Balloon
                            closable={false}
                            trigger={
                              <ButtonIcon
                                name="question-line"
                                style={{ marginLeft: 4, display: 'inline-block' }}
                              />
                            }
                            align="t"
                          >
                            <a href={docs('crypto')} target="_blank" rel="noreferrer">
                              {intl.get({
                                id: 'code-assets.containers.cryptoForm.LearnMore',
                                defaultMessage: '了解更多',
                              })}
                            </a>
                          </Balloon>
                        </>
                      }
                      operation={
                        <CryptoForm setDeleteBtnDisableByCrypto={this.setDeleteBtnDisableByCrypto} />
                      }
                      description={intl.get({
                        id: 'code-assets.containers.cryptoForm.AutomaticEncryptionOfDataStorage',
                        defaultMessage:
                          '数据存储自动加密，可信成员访问自动解密，加固核心代码存储安全。',
                      })}
                      style={{ paddingBottom: 20 }}
                    />
                  :
                  null
                }
                <Section
                  title={intl.get({
                    id: 'code-assets.containers.dagenrousForm.HighRiskOperations',
                    defaultMessage: '高危操作',
                  })}
                >
                  <DagenrousForm
                    {...this.props}
                    searchNamespaces={searchNamespaces}
                    transfer={transfer}
                    archiveOrUnarchive={archiveOrUnarchive}
                    name={projectInfo.name}
                    path={projectInfo.path}
                    httpUrl={projectInfo.http_url_to_repo}
                    rename={rename}
                    isArchived={projectInfo.archived}
                    remove={remove}
                    fullName={projectInfo.name_with_namespace}
                    isRemoving={isRemoving}
                    isTransferring={isTransferring}
                    is_crypto_enabled={is_crypto_enabled}
                  />
                </Section>
                {this.notShowStorageForm() ? null : (
                  <Section
                    title={intl.get({
                      id: 'code-assets.containers.storageForm.BucketManagement',
                      defaultMessage: '存储空间管理',
                    })}
                  >
                    <StorageForm {...this.props} />
                  </Section>
                )}
              </>
            )}
          </>
        )}
      </div>
    );
  }
}

export default connect(
  (state) => ({
    ...state.project.projectSettings.settings,
    pageInfo: state.root.pageInfo,
    lfsInfo: state.project.projectSettings.root.lfsInfo,
  }),
  (dispatch) => bindActionCreators(actions, dispatch),
)(Root);
